package org.jeecg.modules.wo.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import org.apache.http.Consts;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class HttpUtils {

    public static String doGet(String httpurl,Map<String,String> header) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            for (Map.Entry<String, String> entry : header.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            connection.disconnect();// 关闭远程连接
        }

        return result;
    }


    public static String doPost(String url,Map<String,String> header,JSONObject jsonObject){
        String result="";
        //CloseableHttpClient实现了HttpClient接口
        CloseableHttpClient httpClient= HttpClients.createDefault();
        HttpPost httpPost=new HttpPost(url);
        //创建HttpClientBuilder设置属性
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(RequestConfig.custom()
                .setConnectionRequestTimeout(6000)
                .setSocketTimeout(6000)
                .setConnectTimeout(6000).build()).setRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

        //设置请求头信息
        Map<String,String> map=new HashMap<>();
        map.put("Accept","application/json, text/plain, */*");
        map.put("Accept-Encoding","gzip, deflate");
        map.put("Accept-Language","zh-CN,zh;q=0.9");
        map.put("Connection","keep-alive");
        map.put("Content-Type","application/json;charset=UTF-8");
        map.put("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.5024.400 QQBrowser/10.0.932.400");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }
        if(header!=null){
            /**
             * 调用传入的header参数
             */
            for (Map.Entry<String, String> entry : header.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        //传递参数为json数据
        //创建指定内容和编码的字符串实体类
        if(jsonObject!=null){
            StringEntity entity=new StringEntity(jsonObject.toString(), Consts.UTF_8);
            httpPost.setEntity(entity);
        }
        //设置请求参数
        // 创建HttpClient对象，CloseableHttpClient实例的生成器
        httpClient=httpClientBuilder.build();
        try {
            // 发送HttpPost请求，获取返回值
            CloseableHttpResponse response=httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //释放资源
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }



  /*  public static void main(String[] args) {
        Integer yCnt=1693;
        Integer allCnt=1704;
        DecimalFormat decimalFormat = new DecimalFormat("0.00%");
        String divide = decimalFormat.format((float) yCnt / (float) allCnt);
        System.out.println(divide);
    }*/
}
